﻿using System;
using System.Threading.Tasks;

namespace CqCore.Messaging
{
    public interface IMessageSubscriber : IDisposable
    {
        Task SubscribeAsync<TMessage>(string topic, Func<TMessage, Task> handler);
        //Next Version
        //Task SubscribeAsync<TEntity>(string topic, Func<Message<TEntity>, Task> handler);
    }

    public static class MessageSubscriberExtensions
    {
        public static async Task SubscribeAsync<TMessage>(this IMessageSubscriber context, string topic, IMessageHandler<TMessage> handler)
        {
            await context.SubscribeAsync<TMessage>(topic, (message) => handler.HandleAsync(message));
        }
        public static async Task SubscribeAsync<TMessage>(this IMessageSubscriber context, IMessageHandler<TMessage> handler)
        {
            await context.SubscribeAsync<TMessage>(typeof(TMessage).FullName.ToLower(), (message) => handler.HandleAsync(message));
        }
    }
}
